//
//  BKAlignedLabel.swift
//  dysaidao
//
//  Created by Penlon Kim on 2023/10/9.
//  Copyright © 2023 kimpl. All rights reserved.
//

import UIKit

class BKAlignedLabel: UILabel {
    
    enum VerticalAlignment {
        case top, middle, bottom
    }
    
    var verticalAlignment: VerticalAlignment = .middle
    
    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
        
        switch verticalAlignment {
        case .top:
            return CGRect(x: bounds.origin.x,
                          y: bounds.origin.y,
                          width: textRect.width,
                          height: textRect.height)
        case .middle:
            return CGRect(x: bounds.origin.x,
                          y: bounds.origin.y + (bounds.height - textRect.height) * 0.5,
                          width: textRect.width,
                          height: textRect.height)
        case .bottom:
            return CGRect(x: bounds.origin.x,
                          y: bounds.origin.y + bounds.height - textRect.height,
                          width: textRect.width,
                          height: textRect.height)
        }
    }
    
    override func drawText(in rect: CGRect) {
        let usedRect = textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines)
        super.drawText(in: usedRect)
    }
    
    static func label(text: String? = nil,
                      font: UIFont = .systemFont(ofSize: 15),
                      bgColor: UIColor = .lightWhiteDark27,
                      textColor: UIColor = .lightBlackDarkWhite,
                      align: NSTextAlignment = .left) -> BKAlignedLabel {
        
        let label = BKAlignedLabel()
        label.backgroundColor = bgColor
        label.textColor = textColor
        label.text = text
        label.numberOfLines = 0
        label.adjustsFontSizeToFitWidth = true
        label.font = font
        label.textAlignment = align
        label.sizeToFit()
        return label
        
    }
}
